package com.eb.service.lmp;

import com.eb.mapper.MiaoshaUserMapper;
import com.eb.pojo.MiaoshaUser;
import com.eb.pojo.MiaoshaUserExample;
import com.eb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import util.IdWorker;
import util.Md5;

import java.util.Date;
import java.util.List;

@Service
public class UserServicelmp implements UserService {
    @Autowired
    private MiaoshaUserMapper miaoshaUserMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public List<MiaoshaUser> list() {
        return miaoshaUserMapper.selectByExample(null);
    }

    @Override
    public int login(MiaoshaUser user) {
        MiaoshaUserExample example = new MiaoshaUserExample();
        MiaoshaUserExample.Criteria criteria = example.createCriteria();
        criteria.andNicknameEqualTo(user.getNickname());
        MiaoshaUser miaoshaUser = null; try {
            miaoshaUser = miaoshaUserMapper.selectByExample(example).get(0);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

        if (miaoshaUser!=null&& Md5.md5Ci(user.getPassword(),1).equals(miaoshaUser.getPassword())){
            redisTemplate.opsForValue().set("user",miaoshaUser.getNickname());
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public void zc(MiaoshaUser user) {
        user.setId(idWorker.nextId());
        user.setPassword(Md5.md5Ci(user.getPassword(),1));
        user.setHead("");
        user.setSalt("1a2b3c");

        miaoshaUserMapper.insert(user);
    }

    @Override
    public MiaoshaUser user() {
        String username = redisTemplate.opsForValue().get("user");
        MiaoshaUserExample example = new MiaoshaUserExample();
        MiaoshaUserExample.Criteria criteria = example.createCriteria();
        criteria.andNicknameEqualTo(username);
        return  miaoshaUserMapper.selectByExample(example).get(0);

    }
}